package net.gz01.wallet.web.controller.customer;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Random;
import java.util.regex.Pattern;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.redis.Redis;

import net.gz01.util.ZODate;
import net.gz01.util.ZOMD5;
import net.gz01.util.ZOMoney;
import net.gz01.util.ZONumberToCN;
import net.gz01.wallet.common.PageRespon;
import net.gz01.wallet.common.TopBank;
import net.gz01.wallet.common.WalletSMS;
import net.gz01.wallet.common.ZOSearchCondition;
import net.gz01.wallet.web.config.SystemEnum;
import net.gz01.wallet.web.controller.BaseController;
import net.gz01.wallet.web.model.*;
import net.gz01.wallet.web.service.CalcFeeService;

public class HomeController extends BaseController{
	private CalcFeeService feeService = new CalcFeeService();
	public void index() {
		MerchUser merchUser = (MerchUser) getSession().getAttribute(MerchUser.SessionKey);
		if (merchUser == null) {
			renderFail("用户未登录");
			return;
		}
		// 今日最新3笔订单
		setAttr("orders", TradeOrder.dao.selectNewestTop(merchUser.getMerchCode(), ZODate.getDate(), 3));
		// 钱包账户
		setAttr("account", Account.dao.select(merchUser.getMerchCode()));
		//搜索一下这个用户最近一个月正在处理中的金额信息
		String sql = "SELECT sum(amount) as proAmt FROM trade_order WHERE merchCode=? AND " +
				"orderStatus in(?,?,?,?,?) AND bizType in(?,?,?,?,?) AND DATE(createTime) BETWEEN ? and ? ";
		String dateTime30 = (ZODate.getPlusDays(ZODate.getDate(), -30L).toString());
		Record record = Db.findFirst(sql, merchUser.getMerchCode(),

				SystemEnum.OrderStatus.FirstReview.getValue(),
				SystemEnum.OrderStatus.SecondReview.getValue(),
				SystemEnum.OrderStatus.ThirdReview.getValue(),
				SystemEnum.OrderStatus.WaitTransferOut.getValue(),
				SystemEnum.OrderStatus.InProcess.getValue(),

				SystemEnum.BizType.TransferOut.getValue(),
				SystemEnum.BizType.Withdraw_Personal.getValue(),
				SystemEnum.BizType.Withdraw_Company.getValue(),
				SystemEnum.BizType.DF_Company.getValue(),
				SystemEnum.BizType.DF_Personal.getValue(),

				dateTime30, ZODate.getDate()
		);
		long proAmt = 0;
		if (record.getLong("proAmt") != null) {
			proAmt = record.getLong("proAmt");
		}
		proAmt = Math.abs(proAmt);
		String show = "￥" + new DecimalFormat(",###,###,##0.00").format(proAmt/100.0);
		setAttr("processShow", show);

		render("home.html");
	}

	public void message() {
		render("message.html");
	}

	public void bill() {
		render("order.html");
	}

	public void withdraw() {
		MerchUser merchUser = (MerchUser) getSession().getAttribute(MerchUser.SessionKey);
		if (merchUser == null) {
			renderFail("用户未登录");
			return;
		}
		setAttr("selfBankCardList", Contacts.dao.select(merchUser.getMerchCode(), "bankCard", true));
		List< Dictionary > usesList = Dictionary.dao.selectByParentKey("userkuaijie");
		setAttr("usesList", usesList);
		setAttr("banks", TopBank.topBankList);
		render("withdraw.html");
	}

	public void transfer() {
		MerchUser merchUser = (MerchUser) getSession().getAttribute(MerchUser.SessionKey);
		if (merchUser == null) {
			renderFail("用户未登录");
			return;
		}
		setAttr("bankCardList", Contacts.dao.select(merchUser.getMerchCode(), "bankCard", false));
		setAttr("walletList", Contacts.dao.select(merchUser.getMerchCode(), "wallet", false));
		setAttr("accountType", getPara());
		// 用途
		List< Dictionary > usesList = Dictionary.dao.selectByParentKey("userkuaijie");
		setAttr("usesList", usesList);
		setAttr("banks", TopBank.topBankList);
//		//转账到他人银行卡的费率
//		TradeConfig tradeConfigDFPer = TradeConfig.dao.select(merchUser.getMerchCode(), SystemEnum.BizType.DF_Personal.getValue());
//		Integer fee = feeService.getFee(100000, tradeConfigDFPer.getFeeId());
//		if(fee>0){//100元收取 fee 分的手续费--对私转账
//			setAttr("feePre", ZOMoney.changeF2Y(Long.parseLong((""+fee))));
//		}
//
//		TradeConfig tradeConfigDFCom = TradeConfig.dao.select(merchUser.getMerchCode(), SystemEnum.BizType.DF_Company.getValue());
//		fee = feeService.getFee(100000, tradeConfigDFCom.getFeeId());
//		if(fee>0){//100元收取 fee 分的手续费--对公转账
//			setAttr("feeCom", ZOMoney.changeF2Y(Long.parseLong((""+fee))));
//		}
		render("transfer.html");
	}

	public void preview() {
		MerchUser user = (MerchUser) getSession().getAttribute(MerchUser.SessionKey);
		if (user == null) {
			renderFail("用户未登录");
			return;
		}
		String amount = getPara("amount");
		if(StrKit.isBlank(amount)) {
			renderFail("提款金额必填");
			return;
		}
		if(!Pattern.compile("(([1-9][0-9]*)|(([0]\\.\\d{1,2}|[1-9][0-9]*\\.\\d{1,2})))").matcher(amount).matches()){
			renderFail("提款金必须是数字且大于0");
			return;
		}
		Contacts contacts = Contacts.dao.findById(getPara("contactsId"));
		if(contacts == null) {
			renderFail("请选择转账用户");
			return;
		}
		if(contacts.getIsStop()!=null && contacts.getIsStop()){
			renderFail("此卡已经禁用，不可操作，如有疑问请联系系统运营商");
			return;
		}
		String payPassword = getPara("payPassword");
		if(StrKit.isBlank(payPassword)) {
			renderFail("支付密码必填");
			return;
		}
		payPassword = ZOMD5.codeFor(getPara("payPassword"));
		if (!payPassword.equals(user.getPayPassword())) {
			renderFail("支付密码错误");
			return;
		}
		// 超过10万要验证短信
		if(new BigDecimal(amount).multiply(new BigDecimal(100)).longValue() >= 10000000) {
			String smscode = getPara("smscode");
			String code =  Redis.use().get(WalletSMS.REDIS_PREFIX + "transfer_" + user.getUserName());
			if(code == null){
				renderFail("短信验证码未获取或已过期");
				return;
			}
			if(!code.equals(smscode)) {
				renderFail("短信验证码错误");
				return;
			}
		}
		// 如果是数据检查则返回json
		if(isParaExists("check")) {
			renderSuccess();
			return;
		}
		setAttr("tradeType", getPara("tradeType"));
		setAttr("contacts", contacts);
		Long allAmt = Long.parseLong(ZOMoney.changeY2F(Double.parseDouble(amount)));
		Integer intAmt = Integer.parseInt(ZOMoney.changeY2F(Double.parseDouble(amount)));
		if("bankCard".equals(contacts.getAccountType()) ){//银行卡
			if (!contacts.getIsSelf()) {//转账
				if (contacts.getIsCompany()) {//对公
					TradeConfig tradeConfigDFCom = TradeConfig.dao.select(user.getMerchCode(), SystemEnum.BizType.DF_Company.getValue());
					Integer fee = feeService.getFee(intAmt, tradeConfigDFCom.getFeeId());
					if (fee > 0) {//100元收取 fee 分的手续费--对公转账
						allAmt += fee;
						setAttr("fee", ZOMoney.changeF2Y(Long.parseLong(("" + fee))));
						setAttr("allAmt", ZOMoney.changeF2Y(allAmt));
					}
				} else {
					TradeConfig tradeConfigDFPer = TradeConfig.dao.select(user.getMerchCode(), SystemEnum.BizType.DF_Personal.getValue());
					Integer fee = feeService.getFee(intAmt, tradeConfigDFPer.getFeeId());
					if (fee > 0) {//100元收取 fee 分的手续费--对私转账
						allAmt += fee;
						setAttr("fee", ZOMoney.changeF2Y(Long.parseLong(("" + fee))));
						setAttr("allAmt", ZOMoney.changeF2Y(allAmt));
					}
				}
			} else {//提现
				if (contacts.getIsCompany()) {//对公
					TradeConfig tradeConfigDFCom = TradeConfig.dao.select(user.getMerchCode(), SystemEnum.BizType.Withdraw_Company.getValue());
					Integer fee = feeService.getFee(intAmt, tradeConfigDFCom.getFeeId());
					if (fee > 0) {//100元收取 fee 分的手续费--对公转账
						allAmt += fee;
						setAttr("fee", ZOMoney.changeF2Y(Long.parseLong(("" + fee))));
						setAttr("allAmt", ZOMoney.changeF2Y(allAmt));
					}
				} else {
					TradeConfig tradeConfigDFPer = TradeConfig.dao.select(user.getMerchCode(), SystemEnum.BizType.Withdraw_Personal.getValue());
					Integer fee = feeService.getFee(intAmt, tradeConfigDFPer.getFeeId());
					if (fee > 0) {//100元收取 fee 分的手续费--对私转账
						allAmt += fee;
						setAttr("fee", ZOMoney.changeF2Y(Long.parseLong(("" + fee))));
						setAttr("allAmt", ZOMoney.changeF2Y(allAmt));
					}
				}
			}
		}
		setAttr("amount", amount);
		setAttr("remark", getPara("remark"));
		setAttr("amountInWords", ZONumberToCN.number2CNMontrayUnit(amount));
		render("preview.html");
	}

	public void chargePreview() {
		MerchUser user = (MerchUser) getSession().getAttribute(MerchUser.SessionKey);
		if (user == null) {
			renderFail("用户未登录");
			return;
		}
		String amount = getPara("amount");
		if(StrKit.isBlank(amount)) {
			renderFail("提款金额必填");
			return;
		}
		String youliAccountId = getPara("youliAccountId");
		YouliAccount youliAccount = YouliAccount.dao.findById(youliAccountId);
		if(youliAccount == null) {
			renderFail("请选择收款银行卡");
			return;
		}
		Long allAmt = Long.parseLong(ZOMoney.changeY2F(Double.parseDouble(amount)));
		Integer intAmt = Integer.parseInt(ZOMoney.changeY2F(Double.parseDouble(amount)));
		TradeConfig tradeConfig = TradeConfig.dao.select(user.getMerchCode(), SystemEnum.BizType.Charge.getValue());
		Integer fee = feeService.getFee(intAmt, tradeConfig.getFeeId());
		if (fee > 0) {//100元收取 fee 分的手续费--对公转账
			allAmt -= fee;
			setAttr("fee", ZOMoney.changeF2Y(Long.parseLong(("" + fee))));
			setAttr("allAmt", ZOMoney.changeF2Y(allAmt));
		}
		setAttr("youliAccount", youliAccount);
		setAttr("amount", amount);
		setAttr("payer", getPara("payer"));
		setAttr("goodsName", getPara("goodsName"));
		setAttr("phoneNo", getPara("phoneNo"));
		setAttr("amountInWords", ZONumberToCN.number2CNMontrayUnit(amount));
		render("chargePreview.html");
	}

	public void orderJson() {
		// 返回数据json
		ZOSearchCondition sc = super.getSearchCondition();
		Page<TradeOrder> pageResult = TradeOrder.dao.search(sc);
		renderJson(new PageRespon(pageResult));
	}

	public void paypswd() {
		MerchUser user = (MerchUser) getSession().getAttribute(MerchUser.SessionKey);
		if (user == null) {
			renderFail("用户未登录");
			return;
		}
		if ("GET".equalsIgnoreCase(getRequest().getMethod())) {
			setAttr("type", getPara());
			render("paypswd.html");
			return;
		}
		String type = getPara("type");
		if ("update".equals(type)) {
			String oldPayPassword = ZOMD5.codeFor(getPara("oldPayPassword"));
			String payPassword = ZOMD5.codeFor(getPara("payPassword"));
			if(!oldPayPassword.equals(user.getPayPassword())) {
				renderFail("旧支付密码错误");
				return;
			}
			user.setPayPassword(payPassword);
			user.setUpdateTime(ZODate.getDateTime());
			user.update();
			renderSuccess();
			return;
		}
		if ("reset".equals(type)) {
			String code =  Redis.use().get(WalletSMS.REDIS_PREFIX + "resetpwd_" + user.getUserName());
			if(code == null){
				renderFail("短信验证码未获取或已过期");
				return;
			}
			String smscode = getPara("smscode");
			if(!code.equals(smscode)) {
				renderFail("短信验证码错误");
				return;
			}
			String payPassword = ZOMD5.codeFor(getPara("payPassword"));
			user.setPayPassword(payPassword);
			user.setUpdateTime(ZODate.getDateTime());
			user.update();
			renderSuccess();
			return;
		}
		if ("loginUpdate".equals(type)) {
			// TODO 登录密码修改
		}
		renderSuccess();
	}


	/**
	 * 给用户手机发送短信验证码
	 */
	public void sendsms() {
		MerchUser user = (MerchUser) getSession().getAttribute(MerchUser.SessionKey);
		if (user == null) {
			renderFail("用户未登录");
			return;
		}
		// 验证码的用途
		String uses = getPara();

		String phoneNo = user.getUserName();
		if (phoneNo == null || phoneNo.length() < 11) {
			renderFail("手机号无效");
			return;
		}
		StringBuilder buff = new StringBuilder();
		Random rd = new Random();
		for (int i = 0; i < 6; i++) {
			buff.append(String.valueOf(rd.nextInt(10)));
		}
		String code = buff.toString();
		Redis.use().setex(WalletSMS.REDIS_PREFIX + uses + "_" + phoneNo, 60, code);
		JSONObject result = null;
		if ("resetpwd".equals(uses)) {
			result = WalletSMS.sendForSetPayPwd(phoneNo, code);
		} else if ("transfer".equals(uses)) {
			String amount = getPara("amount");
			long amt = 0;
			try {
				amt = new BigDecimal(amount).multiply(new BigDecimal(100)).longValue();
			} catch (NumberFormatException e) {
				renderFail("金额错误");
				return;
			}
			result = WalletSMS.sendForExpend(phoneNo, code, amt);
		} else {
			result = new JSONObject();
			result.put("Message", "不支持的短信用途");
		}
		if ("OK".equals(result.getString("Code"))) {
			renderSuccess("验证码已成功发送至尾号" + phoneNo.substring(phoneNo.length() - 4) + "的手机上");
		} else {
			renderFail(result.getString("Message"));
		}
	}

}
